from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.shortcuts import render, redirect, reverse
from django.urls import reverse_lazy
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from .forms import *
from .models import *
from django.contrib.auth.views import auth_login, auth_logout
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail
from itsdangerous import URLSafeTimedSerializer as Serializer
from itsdangerous import SignatureExpired, BadSignature
from django.conf import settings


@login_required
def center(request):
    import datetime
    if request.method == 'POST':
        cuif = UserInfoChangeForm(data=request.POST, files=request.FILES, initial={
            'username': request.POST['username']
        })
        if cuif.is_valid():
            request.user.username = cuif.cleaned_data['username']
            request.user.head = cuif.cleaned_data['head']
            request.user.save()
            return HttpResponse("保存成功")

        else:
            cuif = UserInfoChangeForm(initial={
                "username": request.user.username
            })
            return render(request, 'user/center.html', {'form': cuif})
    else:
        cuif = UserInfoChangeForm(initial={
            "username": request.user.username
        })
        return render(request, 'user/center.html', {'form': cuif, 'date': datetime.datetime.now()})


@login_required
def change_password(request):
    if request.method == 'POST':
        cgf = UserPassWordChangeForm(request.POST)
        if cgf.is_valid():
            if request.user.check_password(cgf.cleaned_data['old_password']):
                request.user.set_password(cgf.cleaned_data['password'])
                request.user.save()

                # 修改密码从新登录
                auth_logout(request)
                return redirect(reverse('user:login'))


            else:
                cgf.add_error("old_password", "原始密码不正确")
                return render(request, 'user/change_password.html', {"form": cgf})
        else:
            return render(request, 'user/change_password.html', {"form": cgf})
    else:
        cgf = UserPassWordChangeForm()
        return render(request, 'user/change_password.html', {"form": cgf})


def make_active_token(user):
    """
    user: 已创建的 User 对象
    expiry: 令牌有效期，单位秒，默认 1 小时
    return: str
    """
    s = Serializer(settings.SECRET_KEY)
    token = s.dumps({'uid': user.id})
    return token


def register(request):
    if request.method == "POST":
        rf = UserRegisterForm(request.POST)
        if rf.is_valid():
            user = rf.save(commit=False)
            user.username = user.email
            user.is_active = False
            user.set_password(rf.cleaned_data['password'])
            user.save()

            token = make_active_token(user)
            active_url = request.build_absolute_uri(
                reverse('user:active', args=[token])
            )

            subject = '账号激活邮件'
            html = f'<a href="{active_url}">点击激活</a>'
            send_mail(subject, '', None, [user.email], html_message=html)

            # send_mail("激活邮件","",None,recipient_list=[user.username],html_message=f"<a href='http://127.0.0.1:8000/user/active/{ user.id }'>激活用户</a>")
            return redirect(reverse('user:login'))
        else:
            return render(request, 'user/register.html', {"form": rf})
    else:
        rf = UserRegisterForm()
        return render(request, 'user/register.html', {"form": rf})


def logout(request):
    auth_logout(request)
    return redirect(reverse('user:login'))


def login(request):
    if request.method == "POST":
        lf = UserLoginForm(request.POST)
        if lf.is_valid():
            # user = CustomUser.objects.filter(username=lf.cleaned_data['username']).first()

            # 用户名邮箱都可以登录
            username_or_email = lf.cleaned_data['username']
            user = CustomUser.objects.filter(username=username_or_email).first()
            if not user:
                user = CustomUser.objects.filter(email=username_or_email).first()
            if user:
                if user.check_password(lf.cleaned_data['password']):
                    auth_login(request, user)
                    return redirect(reverse('main:index'))
                else:
                    lf.add_error("password", "密码错误")
                    return render(request, 'user/login.html', {"form": lf})
            else:
                lf.add_error("username", "用户名不存在")
                return render(request, 'user/login.html', {"form": lf})
        else:
            return render(request, 'user/login.html', {"form": lf})

    else:
        lf = UserLoginForm()
        return render(request, 'user/login.html', {"form": lf})


# def active(request,id):
#     user = CustomUser.objects.filter(id=id).first()
#     if user:
#         user.is_active = True
#         user.save()
#         return redirect(reverse('user:login'))
#     else:
#         HttpResponse("激活失败")


def active(request, token):
    s = Serializer(settings.SECRET_KEY)
    try:
        data = s.loads(token)
        uid = data.get('uid')
        user = CustomUser.objects.get(pk=uid)
    except (SignatureExpired, BadSignature, CustomUser.DoesNotExist):
        return HttpResponse('激活链接无效或已过期')
    if user.is_active:
        return HttpResponse('账号已激活，无需重复操作')

    user.is_active = True
    user.save(update_fields=['is_active'])
    return redirect(reverse('user:login'))


@login_required
def change_head(request):
    if request.method == "POST":
        hcf = UserHeadChangeForm(request.POST, request.FILES)
        if hcf.is_valid():
            head_file = hcf.cleaned_data.get('head')
            if head_file:
                request.user.head = head_file
            else:
                # 选择为空则重置为默认头像
                request.user.head = "head/head.png"
            request.user.save(update_fields=["head"])
            return redirect(reverse('user:center'))
        return render(request, 'user/change_head.html', {"form": hcf})
    else:
        hcf = UserHeadChangeForm()
        return render(request, 'user/change_head.html', {"form": hcf})


@login_required
def change_username(request):
    if request.method == "POST":
        ucf = UserUsernameChangeForm(request.POST)
        if ucf.is_valid():
            username = ucf.cleaned_data.get('username')
            if username:
                # 可选：先校验是否被占用
                if CustomUser.objects.filter(username=username).exclude(pk=request.user.pk).exists():
                    ucf.add_error('username', '该用户名已被占用')
                else:
                    request.user.username = username
                    request.user.save(update_fields=['username'])
                    return redirect(reverse('user:center'))
        # 表单无效或占用，回显错误
        return render(request, 'user/change_username.html', {'form': ucf})
    else:
        ucf = UserUsernameChangeForm(initial={'username': request.user.username})
        return render(request, 'user/change_username.html', {'form': ucf})


